package net.tv90.auth.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.constraints.Email;
import net.tv90.auth.aop.annotation.AccessLimit;
import net.tv90.auth.exception.AuthException;
import net.tv90.auth.model.dto.RegistrationByEmailDTO;
import net.tv90.auth.service.RegisterService;
import net.tv90.auth.service.SMSCodeService;
import net.tv90.auth.utils.web.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


@RestController
@CrossOrigin
@RequestMapping("/register")
@Validated
public class RegisterController {

    @Autowired
    RegisterService registerService;

    @Autowired
    SMSCodeService codeService;

    @AccessLimit(seconds = 20, maxCount = 5)
    @PostMapping("/email")
    public Result registerByEmail(@Validated @RequestBody RegistrationByEmailDTO dto, HttpServletRequest request) {
        try {
            return Result.success(registerService.registerByEmail(dto, request));
        } catch (AuthException e) {
            return Result.failed(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed("服务器错误");
        }
    }

    @AccessLimit(seconds = 60, maxCount = 1)
    @GetMapping("/email/{email}")
    public Result getCode(@PathVariable @Email String email) {
        codeService.sendCodeToEmail(email);
        return Result.success("success");
    }


}
